from .basehandler import require_login, BaseHandler, UserGetter
from . import models

Article = models.Article

class DefaultHandler(BaseHandler):
	_template_dir = 'article'

	def view(self):
		article_id = self.get_arg('id')
		article = self.get_or_404(models.Article, '文章不存在', id=article_id)

		# 更新访问量
		article.view_count += 1
		article.save()
		
		hot = self._hot().exclude(id=article_id)

		return self.render(
			article=article,
			hot=hot[:10],
			author_other=hot.filter(author=article.author),
			comments=models.ArticleComment.objects.filter(article=article),
		)

	@require_login
	def comment(self):
		if self.is_post:
			article_id = self.get_arg('id')
			article = self.get_or_404(models.Article, '文章不存在', id=article_id)
			body = self.get_arg('body')
			models.ArticleComment.objects.create(article=article, body=body, user=self.user)
			article.comment_count += 1
			article.save()
			return self.redirect('view?id=' + article_id)
		else:
			return self.goback()

	def _hot(self):
		"""热门文章"""
		return Article.find_public().order_by('-view_count')